import 'ol/ol.css';

import Map from 'ol/Map.js';
import View from 'ol/View.js';
import Icon from 'ol/style/Icon';
import Style from 'ol/style/Style';
import Fill from 'ol/style/Fill';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import Point from 'ol/geom/Point';
import Polygon from 'ol/geom/Polygon';
import Feature from 'ol/Feature';

import { getScaleFactor } from "@src/utils/OpenlayersCommon.js";

const CENTER = [0.0, 0.0];
const MAP_DEFAULT_ZOOM = 10.0;

/** 初始化openlayers地图 */
const initOpenlayers = (id) => {
    const map = new Map({ target: id });
    const view = new View({ projection: "EPSG:3857", center: CENTER, zoom: MAP_DEFAULT_ZOOM, });
    map.setView(view);
    return { map, view };
}

export const initialize = (id) => {
    const { map, view } = initOpenlayers(id);
    const vectorSource = new VectorSource();
    const vectorLayer = new VectorLayer({ source: vectorSource });
    map.addLayer(vectorLayer);

    const createAHT = (vectorSource) => {
        const scaleFactor = 0.5;
        const status = {
            position: CENTER,
            rotation: Math.PI / 4
        };

        // AHT 智能小车
        const ahtImageAnchor = new Point(status.position); // 以几何点作为锚点
        const ahtFeature = new Feature({ geometry: ahtImageAnchor });
        vectorSource.addFeature(ahtFeature);
        const ahtIcon = new Icon({ src: "/aht.png", anchor: [0.5, 0.5], rotation: 0.0, scale: 0.0 });
        ahtFeature.setStyle(new Style({ image: ahtIcon }));
        ahtFeature.getStyle().getImage().update = () => {
            ahtImageAnchor.setCoordinates(status.position);
            ahtIcon.setRotation(status.rotation);
            const scale = scaleFactor * getScaleFactor(view.getZoom(), MAP_DEFAULT_ZOOM);
            ahtIcon.setScale(scale);
        }

        // CONTAINER 集装箱
        const calculateContainerCoords = () => {
            const centerX = status.position[0];
            const centerY = status.position[1];
            const containerXLength = 2000;
            const containerYLength = 12000;
            const newCoordinates = [[
                [centerX - containerXLength / 2, centerY - containerYLength / 2],
                [centerX + containerXLength / 2, centerY - containerYLength / 2],
                [centerX + containerXLength / 2, centerY + containerYLength / 2],
                [centerX - containerXLength / 2, centerY + containerYLength / 2],
                [centerX - containerXLength / 2, centerY - containerYLength / 2]
            ]];
            return newCoordinates;
        };
        const containerPolygon = new Polygon(calculateContainerCoords());
        const containerFeature = new Feature();
        containerFeature.setGeometry(containerPolygon);
        containerFeature.setStyle(new Style({ fill: new Fill({ color: "#47EE1D" }), zIndex: 1 }));
        vectorSource.addFeature(containerFeature);
        containerFeature.getGeometry().update = () => {
            const scale = scaleFactor * getScaleFactor(view.getZoom(), MAP_DEFAULT_ZOOM);
            containerPolygon.setCoordinates(calculateContainerCoords(status.position, scale));
            containerPolygon.rotate(-status.rotation, status.position);
        }
        containerFeature.getGeometry().update(status.position);

        // exports
        const update = (postionIn, rotationIn) => {
            if (Array.isArray(postionIn) && postionIn.length >= 2) { status.position = postionIn; }
            if (Number.isFinite(rotationIn)) { status.rotation = rotationIn; }
            ahtFeature.getStyle().getImage().update();
            containerFeature.getGeometry().update();
        }

        update(status.position, status.rotation);

        return { status, update };
    }

    const aht = createAHT(vectorSource);

    view.on("change:resolution", () => {
        aht.update();
    });

    const moveFeature = () => {
        const x = aht.status.position[0];
        const y = aht.status.position[1];
        const rotation = aht.status.rotation;
        const speed = 10;
        const dltX = speed * Math.cos(Math.PI / 2 - rotation);
        const dltY = speed * Math.sin(-Math.PI / 2 + rotation);

        let pixelRoundEnabled = false; // 是否使用pixcelround进行更新
        if (map && map.getPixelFromCoordinate) {
            const pixelCoord = map.getPixelFromCoordinate([x, y]);
            if (Array.isArray(pixelCoord) && pixelCoord.length >= 2) {
                const integerPixelCoord = [Math.round(pixelCoord[0] + dltX), Math.round(pixelCoord[1] + dltY)];
                const geographicCoord = map.getCoordinateFromPixel(integerPixelCoord);
                aht.update(geographicCoord);
                pixelRoundEnabled = true;
            }
        }

        if (!pixelRoundEnabled) {
            aht.update([x + dltX, y + dltY]);
        }

    }

    setInterval(() => { moveFeature(); }, 500);
};